import React, {Component} from 'react';
import { FlatList, ActivityIndicator, Platform, DeviceInfo, StyleSheet, Text, View, RefreshControl} from 'react-native';
import { connect } from 'react-redux';
import actions from '../action/index';
import {
    createMaterialTopTabNavigator,
} from "react-navigation";
import NavigationUtil from '../navigator/NavigationUtil';
import PopularItem from '../common/PopularItem';
import NavigationBar from '../common/NavigationBar';
import Toast from 'react-native-easy-toast';

const URL = 'https://api.github.com/search/repositories?q=';
const QUERY_STR = '&sort=stars';
const THEME_COLOR = '#667788';

type Props = {};
export default class PopularPage extends Component<Props> {
    constructor(props) {
        super(props);
        console.log(NavigationUtil.navigation);
        this.tabNames = ['Java', 'Android', 'iOS', 'React', 'React Native', 'PHP'];
    }

    _genTabs() {
        const tabs = {};
        this.tabNames.forEach((item, index) => {
        tabs[`tab${index}`] = {
            screen: props => <PopularTabPage {...props} tabLabel={item}/>,
            navigationOptions: {
                title: item
            }
        }
        });
        return tabs;
    }

    render() {
        let statusBar = {
            backgroundColor: THEME_COLOR,
            barStyle: 'light-content',
        };
        let navigationBar = <NavigationBar
            title={'最热'}
            statusBar={statusBar}
            style={{backgroundColor: THEME_COLOR}}
        />;
        const TabNavigator = createMaterialTopTabNavigator(
            this._genTabs(), {
                tabBarOptions: {
                tabStyle: styles.tabStyle, // 设置 minwidth 后，安卓加载慢，
                upperCaseLabel: false,//是否使标签大写，默认为true
                scrollEnabled: true,//是否支持 选项卡滚动，默认false
                style: {
                    backgroundColor: '#678',//TabBar 的背景颜色
                    height: 30, // fix 开启 scrollEnabled 后 在安卓初次加载闪烁的问题
                },
                indicatorStyle: styles.indicatorStyle,//标签指示器的样式
                labelStyle: styles.labelStyle,//文字的样式
                }
            }
        );
        return <View style={{flex: 1, marginTop: DeviceInfo.isIPhoneX_deprecated ? 30 : 0}}>
            {navigationBar}
            <TabNavigator/>
        </View>
    }
}

const pageSize = 10; // 设为常量，防止修改
class PopularTab extends Component<Props> {

    constructor(props) {
        super(props);
        const { tabLabel } = this.props;
        this.storeName = tabLabel;
    }

    componentDidMount() {
        this.loadData();
    }

    loadData(loadMore) {
        const { onRefreshPopular, onLoadMorePopular } = this.props;
        const store = this._store();
        const url = this.genFetchUrl(this.storeName);
        if (loadMore) {
            onLoadMorePopular(this.storeName, ++store.pageIndex, pageSize, store.items, () => {
                this.refs.toast.show('没有更多了');
            })
        } else {
            onRefreshPopular(this.storeName, url, pageSize);
        }
    }

    _store() {
        const {popular} = this.props;
        let store = popular[this.storeName];
        if (!store) {
            store = {
                items: [],
                isLoading: false,
                projectModes: [], // 要显示的数据
                hideLoadingMore: true, // 默认隐藏加载更多
            }
        }
        return store;
    }

    genFetchUrl(key) {
        return URL + key + QUERY_STR;
    }

    renderItem(data) {
        const item = data.item;
        return <PopularItem 
            item = {item}
            onSelect = {() => {
                NavigationUtil.goPage({
                    projectModel: item
                }, 'DetailPage')
            }}
        />
    }

    genIndicator() {
        return this._store().hideLoadingMore ? null : 
            <View style={styles.indicatorContainer}>
                <ActivityIndicator
                    style = {styles.indicator}
                />
                <Text>正在加载更多..</Text>
            </View>
    }

    render() {
        const { popular } = this.props;
        let store = this._store(); // 动态获取state

        if (!store) {
            store = {
                items: [],
                isLoading: false,
            }
        }
        return (
            <View style={styles.container}>
                <FlatList 
                    data={store.projectModes}
                    renderItem = {data => this.renderItem(data)}
                    keyExtractor = {item => "" + item.id}
                    refreshControl = {
                        <RefreshControl 
                            title = {'Loading'}
                            titleColor = {THEME_COLOR}
                            colors = {[THEME_COLOR]}
                            refreshing = {store.isLoading}
                            onRefresh = {() => this.loadData()}
                            tintColor = {THEME_COLOR}
                        />
                    }
                    ListFooterComponent = { () => this.genIndicator()}
                    onEndReached = {() => {
                        console.log('---onEndReached----');
                        setTimeout(() => {
                            if (this.canLoadMore) {
                                this.canLoadMore = false;   // 不允许加载更多
                                this.loadData(true);
                            }
                        }, 100); // 防止意外 确保刷新在 滚动之后触发
                    }}
                    onEndReachedThreshold = {0.5}
                    onMomentumScrollBegin = {() => {   // 开始滚动，
                        this.canLoadMore = true;  // 只有滚动时，才打开加载更多开关, 避免 FlatList 首次加载就触发  '---onEndReached----'
                        console.log('---onMomentumScrollBegin----');
                    }}
                />
                <Toast ref = {'toast'}
                    position = {'center'}
                />
            </View>
        );
    }
}

const mapStateToProps = state => ({
    popular: state.popular
});

const mapDispatchToProps = dispatch => ({
    onRefreshPopular: (storeName, url, pageSize) => dispatch(actions.onRefreshPopular(storeName, url, pageSize)),
    onLoadMorePopular: (storeName, pageIndex, pageSize, items, callBack) => dispatch(actions.onLoadMorePopular(storeName, pageIndex, pageSize, items, callBack)),
});

const PopularTabPage = connect(mapStateToProps, mapDispatchToProps)(PopularTab);

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    tabStyle: {
        // minWidth: 50,  // fix  minWidth 会导致 tabStyle 初次加载时闪烁
        padding: 0,
    },
    indicatorStyle: {
        height: 2,
        backgroundColor: 'white'
    },
    labelStyle: {
        fontSize: 13,
        margin: 0,
    },
    indicatorContainer: {
        alignContent: 'center',
    },
    indicator: {
        color: 'red',
        margin: 10
    },
});
